package org.csu.mypetstore.api.controller;

import com.alipay.api.AlipayApiException;
import lombok.extern.slf4j.Slf4j;
import org.csu.mypetstore.api.common.CommonResponse;
import org.csu.mypetstore.api.service.CartService;
import org.csu.mypetstore.api.service.OrderService;
import org.csu.mypetstore.api.service.PayService;
import org.csu.mypetstore.api.vo.AlipayBean;
import org.csu.mypetstore.api.vo.CartVO;
import org.csu.mypetstore.api.vo.OrderVO;
import org.csu.mypetstore.api.vo.SimpleOrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.List;

@Slf4j
@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private CartService cartService;
    @Autowired
    private PayService payService;

    // 根据用户名username获取orders入口列表(SimpleOrder)
    @GetMapping("/user/{username}/orders")
    @ResponseBody
    public CommonResponse<List<SimpleOrderVO>> getOrderListByUser(@PathVariable("username") String username) {
        return orderService.getSimpleOrdersByUsername(username);
    }

    // 根据orderId获取单个order的详细信息
    @GetMapping("/user/orders/{id}")
    @ResponseBody
    public CommonResponse<OrderVO> getOrderById(@PathVariable("id") String id) {
        try {
            int orderId = Integer.parseInt(id);
            return orderService.getOrderById(orderId);
        } catch (Exception e) {
            log.error("订单编号参数错误", e);
            return CommonResponse.createForArgument("订单编号参数id错误");
        }
    }

    // 创建新的订单并跳转到支付页面(请求转发)
    @PostMapping("/orders")
    public ModelAndView createOrder(OrderVO orderVO, HttpSession session) {
        CartVO cartVO = (CartVO) session.getAttribute("cart");
        CartVO cart = cartService.mergeCarts(cartVO, null);
        CommonResponse response = orderService.initOrder(cart, orderVO);
        if (!response.isSuccess()) {
            // 出现错误就直接返回
            ModelAndView errorMav = new ModelAndView("/order/error");
            errorMav.addObject("response", response);
            return errorMav;
        }
        // OrderVO此时已经在initOrder方法中完成所有的初始化工作
        session.setAttribute("forward_order", orderVO.getOrderId());
        // 请求转发的参数注入
        ModelAndView successMav = new ModelAndView("/order/pay/alipay");
        successMav.addObject("out_trade_no", orderVO.getOrderId());
        successMav.addObject("subject", orderVO.getUsername());
        successMav.addObject("total_amount", orderVO.getTotalPrice());
        successMav.addObject("body", new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(orderVO.getOrderDate()));
        return successMav;
    }

    // 订单完成支付后修改订单状态为"P"
    @PatchMapping("/pay/status")
    @ResponseBody
    public CommonResponse paidOrder(HttpSession session) {
        int orderId = (int) session.getAttribute("forward_order");
        return orderService.payOrder(orderId);
    }

    @PostMapping("/pay/alipay")
    public void alipay(AlipayBean alipayBean, HttpServletResponse response) throws IOException, AlipayApiException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println(payService.aliPay(alipayBean));
    }

    @PostMapping("/error")
    @ResponseBody
    public CommonResponse orderError(@RequestParam("response") CommonResponse response) {
        return response;
    }
}
